package com.tsoj.tsojjudgeservice.judge.codesandbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.tsoj.common.ErrorCode;
import com.tsoj.context.ThreadLocalContext;
import com.tsoj.exception.BusinessException;
import com.tsoj.model.codesandbox.ExecuteCodeRequest;
import com.tsoj.model.codesandbox.ExecuteCodeResponse;
import com.tsoj.tsojjudgeservice.judge.codesandbox.CodeSandbox;
import com.tsoj.utils.ApiSignatureAuth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 远程代码沙箱(准备调用docker)
 */
@Component
public class RemoteCodeSandbox implements CodeSandbox {
    //进行api签名认证 远程调用接口
//    @Resource
//    private ApiSignatureAuth apiSignatureAuth;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        //进行api签名认证 远程调用接口
        HashMap<String, String> params = new HashMap<>();
        Long userId = ThreadLocalContext.getUserId();
        params.put("userId",String.valueOf(userId));
        params.put("language",executeCodeRequest.getLanguage());
        String signature = ApiSignatureAuth.generateSignature(params);

        //调用接口
        String url = "http://127.0.0.1:8090/executeCode";
        Map<String, Object> allParams = new HashMap<>();
        allParams.put("executeCodeRequest",executeCodeRequest);
        allParams.put("params",params);
        allParams.put("signature",signature);
        String jsonStr = JSONUtil.toJsonStr(allParams);
        String result = HttpUtil.createPost(url)
                .header("Content-Type","application/json")
                .body(jsonStr)
                .execute()
                .body();

        if(StringUtils.isBlank(result)){
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR,"executeCode error");
        }
        //返回结果
        return JSONUtil.toBean(result, ExecuteCodeResponse.class);
    }
}
